package com.dunqi.gpm.cangxi;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.dunqi.gpm.cangxi.common.base.BaseAct;
import com.dunqi.gpm.cangxi.develop.fragment.DevelopFragment;
import com.dunqi.gpm.cangxi.home.fragment.HomeFragment;
import com.dunqi.gpm.cangxi.mine.fragment.MyFragment;
import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;

import java.util.ArrayList;

import butterknife.BindView;

public class MainActivity extends BaseAct implements RadioGroup.OnCheckedChangeListener {
    @BindView(R.id.home_rb)
    RadioButton homeRb;
    @BindView(R.id.develop_rb)
    RadioButton developRb;
    @BindView(R.id.my_rb)
    RadioButton myRb;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    ArrayList<RadioButton> views = new ArrayList<>();
    ArrayList<Fragment> fragments = new ArrayList<>();

    @Override
    protected void refreshData(Bundle savedInstanceState) {
//        Disposable subscribe = UpgradeUtil.upgradeCheck(this);
//        addDisposables(subscribe);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!update_hint)//没有检查过采取检查
            checkPermission();
    }

    @Override
    protected void initUiAndListener() {
        checkPermission();
        initRadioButton();
        fragments.add(new DevelopFragment());
        fragments.add(new HomeFragment());
        fragments.add(new MyFragment());
        switchFragment(fragments.get(1));
    }

    boolean update_hint = false;

    private void checkUpdate() {
        PgyUpdateManager.register(MainActivity.this,
                new UpdateManagerListener() {
                    @Override
                    public void onUpdateAvailable(final String result) {
                        update_hint = true;
                        // 将新版本信息封装到AppBean中
                        final AppBean appBean = getAppBeanFromString(result);
                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("新版本")
                                .setMessage(appBean.getReleaseNote())
                                .setNegativeButton(
                                        "更新",
                                        (dialog, which) -> startDownloadTask(MainActivity.this, appBean.getDownloadURL())
                                ).show();
                    }

                    @Override
                    public void onNoUpdateAvailable() {
                        update_hint = true;
                    }
                });
    }

    private void initRadioButton() {
        views.add(developRb);
        views.add(homeRb);
        views.add(myRb);
        radioGroup.setOnCheckedChangeListener(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    public void switchFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        for (Fragment fragment1 : fragments) {
            if (fragment1.isAdded()) {
                fragmentManager.beginTransaction().hide(fragment1).commit();
            }
        }

        if (fragment.isAdded()) {
            fragmentManager.beginTransaction().show(fragment).commit();
        } else {
            fragmentManager.beginTransaction().add(R.id.container, fragment).commit();
        }
    }

    @Override
    public View getStateView() {
        return null;
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.develop_rb:
                switchFragment(fragments.get(0));
                break;
            case R.id.home_rb:
                switchFragment(fragments.get(1));
                break;
            case R.id.my_rb:
                switchFragment(fragments.get(2));
                break;
        }
    }

    public void select(int index) {
        views.get(index).performClick();
    }

    public void checkPermission() {
//        int checkINSTALL = ActivityCompat.checkSelfPermission(this, android.Manifest.permission.REQUEST_INSTALL_PACKAGES);
        int checkSelfPermission = ActivityCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (checkSelfPermission == PackageManager.PERMISSION_GRANTED) {     //允许  0,  询问  -1
            //已经获取到权限  获取用户媒体资源
            checkUpdate();
        } else {
            //没有拿到权限  是否需要在第二次请求权限的情况下
            // 先自定义弹框说明 同意后在请求系统权限(就是是否需要自定义DialogActivity)
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1514);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (1514 == requestCode) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        new AlertDialog.Builder(this).setTitle("提示").setMessage("为保障更新功能正常运行,请设置允许读写权限!").setNegativeButton("去设置", (dialog, which) -> {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_SETTINGS);
                            startActivity(intent);
                        }).show();
                    }
                    if (permissions[i].equals(Manifest.permission.READ_PHONE_STATE)) {
                        new AlertDialog.Builder(this).setTitle("提示").setMessage("为了识别您的唯一性,请允许程序读取设备信息!").setNegativeButton("去设置", (dialog, which) -> {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_SETTINGS);
                            startActivity(intent);
                        }).show();
                    }
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}